import { IFormRule } from './types/form'
import request from '@/utils/request'
import { FileItem, FileCategory } from './types/file'

/**
 * 获取附件图片列表
 * @param params
 * @returns
 */
export const getFiles = (params: {
  page: number
  limit: number
  pid: number
}) => {
  return request<{
    count: number
    list: FileItem[]
  }>({
    method: 'GET',
    url: '/file/file',
    params
  })
}

/**
 * 获取附件图片分类创建表单规则
 * @param params
 * @returns
 */
export const getCreateCategoryRule = (params: { id?: number }) => {
  return request<{ rules: IFormRule[] }>({
    method: 'GET',
    url: '/file/category/create',
    params
  }).then(data => {
    return data.rules
  })
}

export const getEditCategoryRule = (id: number) => {
  return request<{ rules: IFormRule[] }>({
    method: 'GET',
    url: `/file/category/${id}/edit`
  }).then(data => {
    return data.rules
  })
}

export const updateFileCategory = (
  id: number,
  data: { pid: number; name: string }
) => {
  return request({
    method: 'PUT',
    url: `/file/category/${id}`,
    data
  })
}

/**
 * 获取附件图片分类
 * @param params
 * @returns
 */
export const getFileCategories = (params: { name: string }) => {
  return request<{
    list: FileCategory[]
  }>({
    method: 'GET',
    url: '/file/category',
    params
  })
}

/**
 * 保存添加附件图片分类
 * @param data
 * @returns
 */
export const saveFileCategory = (data: { pid?: number; name: string }) => {
  return request({
    method: 'POST',
    url: '/file/category',
    data
  })
}

/**
 * 上传附件图片
 * @param data
 * @returns
 */
export const uploadFile = (data: { pid: number; file: File }) => {
  const fd = new FormData()
  fd.append('pid', data.pid.toString())
  fd.append('file', data.file)
  return request<{
    list: FileCategory[]
  }>({
    method: 'POST',
    url: '/file/upload',
    data: fd
  })
}

/**
 * 附件图片上传
 * @param data
 * @returns
 */
export const uploadAttacFile = (data: { pid: number; file: File }) => {
  const fd = new FormData()
  fd.append('pid', data.pid.toString())
  fd.append('file', data.file)
  return request<{
    list: FileCategory[]
  }>({
    method: 'POST',
    url: '/files/attac_upload',
    data: fd
  })
}

/**
 * 修改附件名称
 * @param id
 * @param real_name
 * @returns
 */
export const updateFilename = (id: number, real_name: string) => {
  return request<{
    src: string
  }>({
    method: 'PUT',
    url: `/file/file/update/${id}`,
    data: { real_name }
  })
}

/**
 * 删除附件
 * @param ids 图片id拼接成的字符串
 * @returns
 */
export const deleteFile = (ids: string) => {
  return request({
    method: 'POST',
    url: '/file/file/delete',
    data: { ids }
  })
}

/**
 * 移动附件图片
 * @param data images是图片id拼接成的字符串
 * @returns
 */
export const moveFiles = (data: { pid: number; images: string }) => {
  return request({
    method: 'PUT',
    url: '/file/file/do_move',
    data
  })
}
